﻿
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Collections.ObjectModel;
using System.Windows.Forms;
using System.Windows.Input;
using Techstar.Common;
using Techstar.Dialog;
using Techstar.Progress;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using MessageBox = System.Windows.MessageBox;
using UserControl = System.Windows.Controls.UserControl;
using SmartMD.Manager.Common;
using SmartMD.DataModel;
using SmartMD.DataModel.Entity;
using SmartMD.DataAccess.Service;
using SmartMD.DataAccess.Interface.Dao;

namespace SmartMD.Manager.SysInfo
{
    public partial class DataDictWindow : BaseWindow
    {

        private string boName;//业务对象ID

        /// <summary>
        /// 字典类别列表
        /// </summary>
        private static ObservableCollection<DictionaryType> _dictionaryTypeList = new ObservableCollection<DictionaryType>();
        private DictionaryType _currentDictionaryType;
        private bool _isChanged;


        public DataDictWindow()
        {
            InitializeComponent();
            this.RegisterToolbar(this.tbBasicDataTool);
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }
            DictionaryList_Loaded(null, null);
            this.Height = double.NaN;
            this.Width = double.NaN;

        }

        private void SyncData(ObservableCollection<DictionaryType> cacheList)
        {
            List<DictionaryType> list = DataServiceManager.DataDictService.loadAllDictianryInfo();
            if (list != null && list.Count > 0)
            {
                foreach (var dictionaryType in list)
                {
                    var ok = false;
                    var isdelete = false;
                    dictionaryType.State = RecordState.Normal;
                    for (var i = 0; i < cacheList.Count; i++)
                    {
                        var template = cacheList[i];
                        if (dictionaryType.Id == template.Id)
                        {
                            //修改和删除状态不做处理
                            if (template.State != RecordState.Modified && template.State != RecordState.Deleted)
                            {
                                cacheList[i] = dictionaryType;
                            }
                            ok = true;
                            break;
                        }

                    }
                    if (!ok)
                        cacheList.Add(dictionaryType);
                }
                //对于状态是nomal并且本地缓存不在数据库记录中的记录从本地缓存删除
                for (int i = 0; i < cacheList.Count; i++)
                {
                    var dictionaryType = cacheList[i];
                    if (list.FirstOrDefault(t => t.Id == dictionaryType.Id) == null &&
                        dictionaryType.State == RecordState.Normal)
                    {
                        cacheList.Remove(dictionaryType);
                        i = i - 1;
                    }
                }

            }
            else
            {
                cacheList.Clear();
            }

        } 

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool Exists(string id, string name)
        {
            return _dictionaryTypeList.FirstOrDefault(t => t.Id != id && t.Name.ToLower() == name.ToLower()) != null;
        }

        #region 字典类别
        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_isChanged)
            {
                MessageBox.Show("字典项改变！请先保存字典项数据", "系统字典项保存", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            _currentDictionaryType = lbDictionary.SelectedItem as DictionaryType;
            if (_currentDictionaryType != null)
                lbDictionaryItem.ItemsSource = _currentDictionaryType.Items;
        }

        void DictionaryList_Loaded(object sender, RoutedEventArgs e)
        {
            ProgressThread progressThread = new ProgressThread(200);
            try
            {
                progressThread.Start("正在加载数据", "正在加载系统字典数据......");
                progressThread.Step = "正在加载系统字典缓存数据......";
                _dictionaryTypeList = LoadCache();
                if (SingletonManager.Online)
                {
                    progressThread.Step = "正在加载系统字典数据......";
                    SyncData(_dictionaryTypeList);
                    SaveCache();
                }
                lbDictionary.ItemsSource = _dictionaryTypeList;

            }
            finally
            {
                progressThread.End();
            }
        }
        #endregion

        public DictionaryType Save(DictionaryType currentDictionaryType)
        {
            var result = currentDictionaryType;

            if (SingletonManager.Online)
            {
               // var id = DataServiceManager.CommonQuery.saveOrUpdateObject(result);               
                //result = DataServiceManager.DictionaryService.GetDictionaryType(id);

                currentDictionaryType.Items.Clear();
                foreach (var item in result.Items)
                {
                    item.DictionaryType = currentDictionaryType;
                    currentDictionaryType.Items.Add(item);
                }
            }
            _isChanged = false;
            ListBox_SelectionChanged(_currentDictionaryType, null);

            this.SaveCache();

            return result;
        }

        public void New()
        {
            DictTypeEdit sysDictTypeEdit = new DictTypeEdit("新建系统字典类别");
            _currentDictionaryType = new DictionaryType();           
            _currentDictionaryType.Id = System.DateTime.Now.ToString("yyyyMMddHHmmss");//System.Guid.NewGuid().ToString();
            sysDictTypeEdit.CurrentDictionaryType = _currentDictionaryType;
            if (sysDictTypeEdit.ShowDialog() == true)
            {
                var result = sysDictTypeEdit.CurrentDictionaryType;
                
                result.State = RecordState.Added;
                
                _dictionaryTypeList.Add(result);
                this.lbDictionary.SelectedItem = result;
                this.lbDictionaryItem.ItemsSource = result.Items;
              
                this.SaveCache();
            }
        }

        public void Edit()
        {
            var selectitem = lbDictionary.SelectedItem as DictionaryType;
            _currentDictionaryType = selectitem;
            if (selectitem == null) return;
            DictTypeEdit sysDictTypeEdit = new DictTypeEdit("编辑系统字典类别");
            sysDictTypeEdit.CurrentDictionaryType = Org.Hessian.Utility.HessianHelper.Clone(_currentDictionaryType);
            if (sysDictTypeEdit.ShowDialog() == true)
            {

                var result = sysDictTypeEdit.CurrentDictionaryType;               
                result.State = RecordState.Modified;
               
                var index = _dictionaryTypeList.IndexOf(selectitem);
                _dictionaryTypeList[index] = result;
                this.lbDictionary.SelectedItem = result;
               
                this.SaveCache();
            }

        }

        public void DeleteDictionaryType()
        {
            var selectitem = lbDictionary.SelectedItem;
            if (selectitem == null)
            {
                MessageBox.Show("没有选择要删除的系统字典类别！", "系统字典类别删除", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            var item = (DictionaryType)selectitem;
            if (MessageBox.Show("是否删除选中的系统字典类别?", "提示信息", MessageBoxButton.YesNo, MessageBoxImage.Question) == (MessageBoxResult)DialogResult.Yes)
            {
                if (SingletonManager.Online)
                {
                    var list = new ObservableCollection<DictionaryType>();
                    list.Add(item);
                   // DataServiceManager.DictionaryService.DeleteDictionaryTypes(list);
                    _dictionaryTypeList.Remove(item);
                }
                else
                {
                    item.State = RecordState.Deleted;
                    _dictionaryTypeList.Remove(item);
                }
            }
            SaveCache();
        }

        public void SyncClick()
        {
            ProgressThread progressThread = new ProgressThread(200);
            try
            {
                progressThread.Start("数据同步", "正在和服务器进行系统字典的数据同步");
                SyncData(_dictionaryTypeList);
        
                progressThread.End();
                this.SaveCache();
                TaskDialogEx.Information("同步成功", "系统字典数据同步成功！");

            }
            catch (Exception err)
            {
                progressThread.End();
                TaskDialogEx.Information("同步失败", "失败原因：" + err.Message);
            }
        }

        public ObservableCollection<DictionaryType> LoadCache()
        {
            var result = SingletonManager.Cache.LoadEntity<ObservableCollection<DictionaryType>>("系统字典", "系统字典列表");
            if (result == null)
                result = new ObservableCollection<DictionaryType>();
            return result;
        }

        public void SaveCache()
        {
            SingletonManager.Cache.SaveEntity("系统字典", "系统字典列表", _dictionaryTypeList);
        }

        public void Commit()
        {
            var items = new ObservableCollection<DictionaryType>();
            foreach (var dictionaryType in _dictionaryTypeList)
            {
                if (dictionaryType.State != RecordState.Normal)
                    items.Add(dictionaryType);
            }
            if (items.Count == 0)
            {
                TaskDialogEx.Warning("没有可以提交到数据服务器的内容!");
                return;
            }

            /* string errMessage;
           if (!MainWindow.Instance.TestServiceConnect(out errMessage))
            {
                System.Windows.MessageBox.Show(errMessage, @"不能提交", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            } */

            new CommitDialog(items).ShowDialog();
        }

        private void btnSearch2_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtSearch2.Text))
                this.lbDictionary.ItemsSource = _dictionaryTypeList;
            else
            {
                var result = new ObservableCollection<DictionaryType>();
                foreach (var dictionaryType in _dictionaryTypeList)
                {
                    var list = new List<string>
                                   {
                                       dictionaryType.Name,
                                       dictionaryType.Code
                                   };
                    if (StringEx.Like(list, txtSearch2.Text.Split(new[] { ' ' })))
                        result.Add(dictionaryType);
                }
                this.lbDictionary.ItemsSource = result;
            }
        }

        private void txtSearch2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter) btnSearch2_Click(null, null);
        }

        private void btnCronExpression_Click(object sender, RoutedEventArgs e)
        {
           
        }

        private void btnSync_Click(object sender, RoutedEventArgs e)
        {
            this.SyncClick();
        }

        private void btnCommit_Click(object sender, RoutedEventArgs e)
        {
            this.Commit();
        }

        private void btnNew_Click(object sender, RoutedEventArgs e)
        {
            this.New();
        }

        private void btnEdit_Click(object sender, RoutedEventArgs e)
        {
            this.Edit();
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            this.DeleteDictionaryType();
        }

        public static string ModuleName { get { return "数据字典"; } }
    }
}
